package com.atguigu.springcloud.service.impl;

import com.atguigu.springcloud.dao.DeptRepository;
import com.atguigu.springcloud.entities.Dept;
import com.atguigu.springcloud.request.SaveDeptRequest;
import com.atguigu.springcloud.service.DeptService;
import com.atguigu.springcloud.utils.ModelMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by luojie on 2018/9/5.
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<Dept> findAll() {
        return deptRepository.findAll();
    }

    @Override
    public Dept findById(String id) {
        String hql = "from Dept d where d.id='" + id + "'";
        Query query = entityManager.createQuery(hql);
        List<Dept> list = query.getResultList();
        if(list == null || list.size() == 0){
            return null;
        }
        return list.get(0);
    }

    @Override
    public Dept save(SaveDeptRequest request) {
        Dept dept = ModelMapperUtil.getStrictModelMapper().map(request, Dept.class);
        dept = deptRepository.save(dept);
        return dept;
    }

    @Override
    public Dept findByDname(String dname) {
        return deptRepository.findByDname(dname);
    }

    @Modifying
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Dept updateCount(Dept dept, Integer count) {
        dept.setCount(dept.getCount() + count);
        return dept;
    }
}
